from rest_framework.response import Response
from rest_framework.views import APIView
from django.conf import settings
from user.models import UserInfo,UserLog,OperationLog
from user.serializers import UserLogSerializer,OperatelogSerializer,UserSerializer
from rest_framework.viewsets import ModelViewSet
from rest_framework import filters
from django_filters.rest_framework import DjangoFilterBackend
import os

#创建用户接口
class UserViewSet(ModelViewSet):
    queryset = UserInfo.objects.all()
    serializer_class = UserSerializer

    filter_backends = [filters.SearchFilter, filters.OrderingFilter, DjangoFilterBackend]
    search_fields = ('username',)
    filterset_fields = ('first_name',)  # 指定过滤的字段

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        res = {'code': 200, 'msg': '创建成功'}
        return Response(res)

    def update(self, request, *args, **kwargs):
        try:
            partial = kwargs.pop('partial', False)
            instance = self.get_object()
            serializer = self.get_serializer(instance, data=request.data, partial=partial)
            serializer.is_valid(raise_exception=True)
            self.perform_update(serializer)
            res = {'code': 200, 'msg': '更新成功'}
        except Exception as e:
            res = {'code': 500, 'msg': '%s' %e}
        return Response(res)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        res = {'code': 200, 'msg': '删除成功'}
        return Response(res)



class UserlogViewSet(ModelViewSet):

    queryset = UserLog.objects.all()    #指定操作的数据
    serializer_class = UserLogSerializer  #指定序列化器
    from rest_framework import filters
    from django_filters.rest_framework import DjangoFilterBackend
    filter_backends = [filters.SearchFilter, filters.OrderingFilter, DjangoFilterBackend]  # 指定过滤器
    search_fields = ('username','first_name',)  # 指定可搜索的字段
    filterset_fields = ('status',)  # 指定过滤的字段


class OperatelogViewSet(ModelViewSet):

    queryset = OperationLog.objects.all()    #指定操作的数据
    serializer_class = OperatelogSerializer  #指定序列化器
    from rest_framework import filters
    from django_filters.rest_framework import DjangoFilterBackend
    filter_backends = [filters.SearchFilter, filters.OrderingFilter, DjangoFilterBackend]  # 指定过滤器
    search_fields = ('username',)  # 指定可搜索的字段
    filterset_fields = ('status',)  # 指定过滤的字段



class CleanLoginLogsView(APIView):
    #清理登录日志
    def post(self, request, *args, **kwargs):
        print(request.data)
        start_time = request.data.get('start_time')
        end_time = request.data.get('end_time')

        try:
            # 删除指定时间范围内的登录日志
            UserLog.objects.filter(create_time__range=(start_time, end_time)).delete()
            res = {'code': 200, 'msg': '清理成功'}
        except Exception as e:
            res = {'code': 500, 'msg': '%s' %e}
        return Response(res)
    #清理操作日志
    def put(self, request, *args, **kwargs):
        print(request.data)
        start_time = request.data.get('start_time')
        end_time = request.data.get('end_time')

        try:
            # 删除指定时间范围内的登录日志
            OperationLog.objects.filter(timestamp__range=(start_time, end_time)).delete()
            res = {'code': 200, 'msg': '清理成功'}
        except Exception as e:
            res = {'code': 500, 'msg': '%s' %e}
        return Response(res)



class VisitEchartView(APIView):

    # 数据格式：
    # X: ['2022-7-11', '2022-7-12', '2022-7-13', '2022-7-14', '2022-7-15', '2022-7-16', '2022-7-16']
    # Y1:  [1, 3, 5, 6, 2, 1, 3]
    # Y2:  [3, 21, 4, 2, 1, 3, 2]

    def get(self, request):
        from datetime import datetime, timedelta
        import pandas as pd

        end = datetime.now()
        start = (end - timedelta(6))
        queryset_obj = UserLog.objects.filter(
            create_time__range=[start, end])  # 或者大于小于 filter(deal_date__gte=week, deal_date__lte=cur_date)

        # 生成时间序列
        date_range = pd.date_range(start=datetime.strftime(start, "%Y-%m-%d"),
                                   end=datetime.strftime(end, "%Y-%m-%d"))  # datetime时间转为日期

        x_data = []
        y_ip_data = []
        y_pv_data = []

        for date in date_range:
            date = datetime.strftime(date, "%Y-%m-%d")
            x_data.append(date)
            y_ip = 0
            y_pv = 0
            for i in queryset_obj:
                date_time = datetime.strftime(i.create_time, "%Y-%m-%d")
                if date == date_time:
                    ip_list = []
                    for i in UserLog.objects.filter(create_time__date=date_time):
                        ip_list.append(i.remote_ip)
                    y_ip = len(set(ip_list))  #统计当天所有的ip,set去重后统计数量
                    # 查询 create_time 字段的日期部分等于 date_time 的所有记录
                    y_pv = UserLog.objects.filter(create_time__date=date_time).count()  # 统计当天所有的pv
            y_ip_data.append(y_ip)
            y_pv_data.append(y_pv)
        data = {'y_ip_data': y_ip_data, 'y_pv_data': y_pv_data, 'x_data': x_data}
        res = {'data': data, 'code': 200, 'msg': '成功'}
        return Response(res)




